package cn.kgc.base.controller;

import cn.hutool.core.util.RandomUtil;
import cn.kgc.commons.constant.HttpExceptionCodeEnum;
import cn.kgc.commons.constant.SystemConstant;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.util.RedisUtil;
import cn.kgc.commons.util.SendPhoneMessage;
import cn.kgc.commons.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: 石浩杰
 * @date: 2022-11-01 10:29
 */
@RestController
@RequestMapping("/code")
@Api(tags = "获得验证码控制器")
@ConditionalOnClass(ResponseBodyAdvice.class)
public class SendCodeController {
    @Resource
    private RedisUtil redisUtil;
    @GetMapping("/send")
    @ApiOperation(value = "获得验证码",httpMethod = "GET",produces = "application/json;charset=utf-8")
    @ApiImplicitParam(name = "phone",value = "手机号",paramType = "query")
    public Result code(@RequestParam("phone") String phone, HttpServletRequest request) throws Exception {
        //15371631421  1234 30s
        String key=SystemConstant.REGISTER_PHONE_CODE+phone;
        if (redisUtil.hasKey(key)){
            throw new HttpException(HttpExceptionCodeEnum.PHONE_CODE_REPEAT.getCode(), HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        //产生随机数验证码
        int code=RandomUtil.randomInt(10000,99999);
        redisUtil.set(key,code,1, TimeUnit.MINUTES);
        System.out.println("验证码："+code);
        SendPhoneMessage.sendPhoneMessage(phone,code+"");
        return Result.ok(code,request.getRequestURL().toString());
        //1 生成验证码:
        //1  该手机号1分钟是否已经获得验证码，如果没有生成验证码，通过阿里的短信接口，发送短信
        //2  如果已经生成过验证码，不能重复获得验证码
    }

}
